package com.lzp.jdbc.datasource.druid;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Properties;

public class DruidTest {
    public static void main(String[] args) throws Exception {
        testDruidConnection();
        testDruidDBUpdate();
    }

    /**
     * 测试druid连接池连接
     *
     * @throws Exception
     */
    public static void testDruidConnection() throws Exception {
        // 加载配置文件
        Properties prop = new Properties();
        prop.load(DruidTest.class.getResourceAsStream("druid.properties"));
        // 获取连接池对象
        DataSource dataSource = DruidDataSourceFactory.createDataSource(prop);
        // 获取连接
        for (int i = 0; i < 11; i++) {
            Connection connection = dataSource.getConnection();
            System.out.println(connection);
            if (i % 2 == 0) {
                connection.close();
            }
        }
    }

    /**
     * 使用druid
     */
    public static void testDruidDBUpdate() {
        Connection connection = null;
        PreparedStatement ps = null;
        try {
            // 获取连接
            connection = DruidUtil.getConnection();
            System.out.println(connection);
            // 定义sql
            String sql = "insert into account_jdbc value(null, ?,?)";
            // 获取PrepareStatement，并赋值
            ps = connection.prepareStatement(sql);
            ps.setString(1, "账户4");
            ps.setDouble(2, 2000);
            // 执行sql
            int result = ps.executeUpdate();
            assert result == 1;
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DruidUtil.close(ps, connection);
        }
    }
}
